package com.dxyxx.framework;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.android.customized.PopMenu;
import com.android.customized.PopMenu.OnPopMenuItemClickListener;
import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.pojo.Order;
import com.dxyxx.pojo.OrderDetail;
import com.dxyxx.pojo.PayType;
import com.dxyxx.pojo.Product;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.pojo.Store;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ta.utdid2.android.utils.StringUtils;

public class GroupOrderConfirmActivity extends BaseActivity {
	private final static String ID = "id";
	private final static String PID = "pid";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS = "imageIds";
	private final static String AMOUNT = "amount";
	private TextView money;
	private List<OrderDetail> products = new ArrayList<OrderDetail>();
	private UserPreferences userPreferences;
	private static ProgressDialog progressDialog;
	private PopMenu deliveryPopUpMenu;
	private PopMenu timePopUpMenu;
	private PopMenu payTypePopUpMenu;
	private TextView storeText;
	private ArrayList<String> storeItems;
	private ArrayList<Integer> storeIds;
	private List<Store> stores;
	//	private EditText et_payType;
	private ArrayList<String> payTypeMenuItems;
	private ArrayList<String> timeMenuItems;
	private ArrayList<Integer> timeMenuIds;
	private PopMenu storePopUpMenu;
	private ImageView refreshImage;
	private Animation anim;
	private ImageView checkout_1;
	private ImageView checkout_2;
	private boolean wechat = true;
	private EditText dtime;
	private EditText bziti;
	private int storeId;// 选择门店id 
	private int timeMenuId;//  选择提货时间id
	private Context context;
	private ArrayList<String> deliveryMenuItems;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_orderconfirm);
		context = this;
		initViews();
		//请求门店。
		refreshImage = (ImageView) findViewById(R.id.refreshImageButton);
		anim = AnimationUtils.loadAnimation(GroupOrderConfirmActivity.this, R.anim.round_loading);
		callStoreList();
		refreshImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				callStoreList();
			}
		});

		/**
		 * 配送方式 选择框架
		 */
		deliveryMenuItems = new ArrayList<String>();
		deliveryMenuItems.add("自提");
		deliveryMenuItems.add("快递");

		deliveryPopUpMenu = new PopMenu(GroupOrderConfirmActivity.this, deliveryMenuItems, R.layout.common_menu, R.layout.item_common_menu, R.dimen.popMenuWidth);
		bziti = (EditText) findViewById(R.id.et_ziti);
		bziti.setFocusable(false);// 设置成flase，这样才能第一次点击就能实现popup效果
		deliveryPopUpMenu.setOnPopMenuItemClickListener(new OnPopMenuItemClickListener() {

			@Override
			public void onItemClick(int index) {
				if (index == 1) {
					SimpleToast.info(getApplicationContext(), "暂时不支持，您再等等");
					return;
				}
				bziti.setText(deliveryMenuItems.get(index));

			}
		});
		bziti.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				deliveryPopUpMenu.showAsDropDown(view, 0, 0);

			}
		});

		/**
		 * 自提时间
		 */
		timeMenuItems = new ArrayList<String>();
		timeMenuItems.add("当天");
		timeMenuItems.add("下单后第二天");
		timeMenuItems.add("下单后第三天");
		timeMenuIds = new ArrayList<Integer>();
		timeMenuIds.add(0);
		timeMenuIds.add(1);
		timeMenuIds.add(2);

		timePopUpMenu = new PopMenu(GroupOrderConfirmActivity.this, timeMenuItems, R.layout.common_menu, R.layout.item_common_menu, R.dimen.popMenuWidth);

		dtime = (EditText) findViewById(R.id.et_dtime);
		dtime.setFocusable(false);// 设置成flase，这样才能第一次点击就能实现popup效果
		timePopUpMenu.setOnPopMenuItemClickListener(new OnPopMenuItemClickListener() {

			@Override
			public void onItemClick(int index) {
				dtime.setText(timeMenuItems.get(index));
				timeMenuId = timeMenuIds.get(index);
			}
		});
		dtime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				timePopUpMenu.showAsDropDown(view, 0, 0);

			}
		});

		/**
		 * 支付方式
		 */
		/**
		 * 支付方式
		 */
		checkout_1 = (ImageView) findViewById(R.id.checkbox_1);
		checkout_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!wechat) {
					checkout_1.setImageResource(R.drawable.check01);
					checkout_2.setImageResource(R.drawable.check02);
					wechat = !wechat;
				}
			}
		});
		checkout_2 = (ImageView) findViewById(R.id.checkbox_2);
		checkout_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (wechat) {
					checkout_2.setImageResource(R.drawable.check01);
					checkout_1.setImageResource(R.drawable.check02);
					wechat = !wechat;
				}
			}
		});

		ViewGroup rootViewGroup = (ViewGroup) findViewById(R.id.content);

		// 查数据库，列举
		//		Cursor cursor = DataQueryUtils.getAll(this);

		double m = 0;
		DecimalFormat df = new DecimalFormat("######0.00");

		Map<String, String> map = new HashMap<String, String>();
		Product product = (Product) getIntent().getSerializableExtra("product");

		View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
		((TextView) view.findViewById(R.id.price)).setText(product.getPrice() + "");
		((TextView) view.findViewById(R.id.description)).setText(product.getDescription());
		((TextView) view.findViewById(R.id.specification)).setText(product.getSpecification());

		((TextView) view.findViewById(R.id.amount)).setText("* 1");
		int pid = Integer.parseInt(product.getId() + "");
		((TextView) view.findViewById(R.id.all)).setText("=" + df.format(product.getPrice()));
		imageLoader.displayImage(HttpUtil.baseImageURL + product.getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);

		rootViewGroup.addView(view);
		// product.setAmount(amount);
		OrderDetail od = new OrderDetail();
		// od.setProduct(product);
		od.setAmount(1);
		od.setPrice(product.getPrice());
		od.setProductId(product.getId());
		// od.setId(1L);

		products.add(od);

		money.setText(df.format(product.getPrice()));

		Button b = (Button) findViewById(R.id.orderConfirmButton);
		userPreferences = UserPreferences.getInstance(getApplicationContext());

		String type = getIntent().getStringExtra("type");
		// 根据type 来判断 哪种url
		if (!StringUtils.isEmpty(type)) {
			if (type.equals("order")) {
			} else if (type.equals("group/add")) { //开团
				title.setText("开团订单确认");
			} else if (type.equals("group/attend")) {
				title.setText("参团订单确认");
			}
		}
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 查看是否 都做了选择。
				if (!isAllSelected()) {
					return;// 没全做了选择， 返回
				}
				// 等待框架
				progressDialog = ProgressDialog.show(GroupOrderConfirmActivity.this, null, null);
				progressDialog.setContentView(R.layout.dialog_circle);
				// 每次 退出之后都要重新获取token。 这时候 要重新登录，处理 失效的情况。

				String urlString = "order/add";
				RequestParams params = new RequestParams();
				String type = getIntent().getStringExtra("type");
				// 根据type 来判断 哪种url
				if (!StringUtils.isEmpty(type)) {
					if (type.equals("order")) {
						urlString = "order/add";
					} else if (type.equals("group/add")) { //开团
						urlString = "gorder/add";
						title.setText("开团订单确认");
						params.add("groupId", getIntent().getStringExtra("groupId"));
					} else if (type.equals("group/attend")) {
						urlString = "gorder/attend";
						title.setText("参团团订单确认");
						params.add("grouInstanceId", getIntent().getStringExtra("instaneceId"));
					}
				}
				params.add("description", "测试");
				if (wechat) {
					params.add("payType", "tenpay");
				} else {
					params.add("payType", "alipay");
				}
				params.add("deliveryType", bziti.getText().toString());
				params.add("storeId", storeId + "");
				params.add("bufferInterval", timeMenuId + "");// 自提时间
				String orderDetails;
				try {
					if (type.equals("order")) {
						orderDetails = getObjectMapper().writeValueAsString(products);
						params.add("orderDetails", orderDetails);
					}
					HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							Log.e("hah", new String(arg2));
							SimpleToast.error(GroupOrderConfirmActivity.this, "有误");
							progressDialog.dismiss();
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// 登陆失效 返回的信息 {"code":0,"info":"没有登陆","object":null}
							try {
								ResponseResult rr = getObjectMapper().readValue(new String(arg2), ResponseResult.class);
								if (rr.getCode() == -1) { // 传递
									// relogin=true;重新登录.
									// 检查是否登录时间 已经超过15天了。
									Intent intent = new Intent(GroupOrderConfirmActivity.this, LoginActivity.class);
									intent.putExtra("relogin", true);
									Toast.makeText(GroupOrderConfirmActivity.this, " 重新获取token", 0).show();
									startActivityForResult(intent, 1);
									// overridePendingTransition(R.style.noAnimation,
									// R.style.noAnimation);

								} else if (rr.getCode() == 0) { // 传递
									Toast.makeText(GroupOrderConfirmActivity.this, rr.getInfo(), 0).show();

								} else {
									Toast.makeText(GroupOrderConfirmActivity.this, "token正常", 0).show();
									// 成功 了 处理订单
									doWithOrder(new String(arg2));
								}
							} catch (JsonParseException e) {
								e.printStackTrace();
							} catch (JsonMappingException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
								progressDialog.dismiss();
							}

						}

					});
				} catch (JsonGenerationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonMappingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// startActivity(new Intent(OrderConfirmActivity.this,
				// PayActivity.class));
			}
		});
	}

	/**
	 * 三个选择 配送方式， 自提门店，自提时间 是否都做了选择
	 * 
	 * @return
	 */
	private boolean isAllSelected() {
		//  配送方式
		if (bziti.getText().toString().equals("请选择")) {
			SimpleToast.info(context, "请选择配送方式");
			return false;
		}
		if (storeText.getText().toString().equals("请选择")) {
			SimpleToast.info(context, "请选择自提门店");
			return false;
		}

		if (dtime.getText().toString().equals("请选择")) {
			SimpleToast.info(context, "请选择自提时间");
			return false;
		}
		return true;
	}

	private void callStoreList() {
		refreshImage.startAnimation(anim);
		refreshImage.setClickable(false);// 禁止重复发送。
		HttpUtil.get("store/list", new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				SimpleToast.error(GroupOrderConfirmActivity.this, "获取门店失败");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				SimpleToast.info(GroupOrderConfirmActivity.this, "获取门店成功");
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(List.class, Store.class);
				try {
					stores = getObjectMapper().readValue(new String(arg2), javaType);
					/**
					 * 配送方式 选择框架
					 */
					storeItems = new ArrayList<String>();
					storeIds = new ArrayList<Integer>();
					for (Store store : stores) {
						storeItems.add(store.getName());
						storeIds.add(store.getId());
					}
					storePopUpMenu = new PopMenu(GroupOrderConfirmActivity.this, storeItems, R.layout.common_menu, R.layout.item_common_menu, R.dimen.popMenuWidth);

					storePopUpMenu.setOnPopMenuItemClickListener(new OnPopMenuItemClickListener() {

						@Override
						public void onItemClick(int index) {
							storeText.setText(storeItems.get(index));
							storeId = storeIds.get(index);
							SimpleToast.info(context, "选择的门店" + storeIds.get(index));
						}
					});
					storeText.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View view) {
							storePopUpMenu.showAsDropDown(view, 0, 0);

						}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFinish() {
				refreshImage.setClickable(true);
				refreshImage.clearAnimation();
				super.onFinish();
			}

		});
	}

	private void doWithOrder(String responseStr) {

		try {
			JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Order.class);
			//报错如下：
			// org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class  com.dxyxx.pojo.User]: can not instantiate from JSON object (need to add/enable type information?)  
			// 解决方法： 为User增加一个无参构造函数

			ResponseResult<Order> result = getObjectMapper().readValue(new String(responseStr), javaType);
			if (result.getCode() == 1) {
				Bundle bundle = new Bundle();
				// Order要实现implements Serializable ，Order 的User成员变量也要实现implements Serializable 
				bundle.putSerializable("order", result.getObject());
				Intent intent = new Intent(GroupOrderConfirmActivity.this, PayActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
			} else {
				Toast.makeText(GroupOrderConfirmActivity.this, result.getInfo(), 0).show();
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	private TextView title;

	public void initViews() {
		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		((ImageView) findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		title = (TextView) findViewById(R.id.title);
		money = (TextView) findViewById(R.id.money);
		title.setText("订单确认");

		title.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		storeText = (TextView) findViewById(R.id.et_store);
		storeText.setFocusable(false);// 设置成flase，这样才能第一次点击就能实现popup效果
	}

	// 重新登录 得到token
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			String result = data.getExtras().getString("result");
			// 查看是否 都做了选择。
			if (!isAllSelected()) {
				return;// 没全做了选择， 返回
			}
			Toast.makeText(GroupOrderConfirmActivity.this, "token 已更新", 0).show();
			String urlString = "order/add";
			RequestParams params = new RequestParams();
			params.add("description", "测试");

			if (wechat) {
				params.add("payType", "tenpay");
			} else {
				params.add("payType", "alipay");
			}
			params.add("deliveryType", bziti.getText().toString());
			params.add("storeId", storeId + "");
			params.add("bufferInterval", timeMenuId + "");// 自提时间
			String orderDetails;
			try {
				orderDetails = getObjectMapper().writeValueAsString(products);
				params.add("orderDetails", orderDetails);
				HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						try {
							ResponseResult rr = getObjectMapper().readValue(new String(arg2), ResponseResult.class);
							if (rr.getCode() == 0) {
								Toast.makeText(GroupOrderConfirmActivity.this, rr.getInfo(), 0).show();

							} else {

								doWithOrder(new String(arg2));
							}
						} catch (JsonParseException e) {
							e.printStackTrace();
						} catch (JsonMappingException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							progressDialog.dismiss();
						}
					}

				});
			} catch (JsonGenerationException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
